<template>
    <view class="time-container df ac jsb">
        <view class="time" @click="openDate">
            <uv-input placeholder="请输入内容" placeholderStyle="font-size:28rpx" fontSize="30rpx" border="none"
                v-model="startTimeCn" readonly>
                <template #suffix>
                    <uv-icon name="arrow-right" size="36rpx"></uv-icon>
                </template>
            </uv-input>
        </view>
        <view class="right">
            <uv-button type="primary" size="small" @click="timePeriodQuery()">
                {{ timeTypeLive == 0 ? '--' : timeTypeLive }}小时
            </uv-button>
        </view>
    </view>
    <view style="height: 800rpx">
        <rainMap :dataList="stationData" v-if="!loading" :maxObj="objMax" />
    </view>
    <!-- <uv-tabs
        :list="tabList"
        @change="tabChange"
        itemStyle="height:88rpx"
        :customeStyle="{ fontSize: '30rpx' }"
        :scrollable="false"
        lineWidth="100rpx"
        lineHeight="6rpx"
    ></uv-tabs> -->
    <view class="station-container m20">
        <view class="top">
            <view class="first">序号</view>
            <view class="second">站名</view>
            <view class="third">雨量</view>
            <view class="fourth" @click="reverseStationData()">
                <uv-image src="/static/rain/top.svg" width="50rpx" height="50rpx"></uv-image>
            </view>
        </view>
        <view class="content" v-if="stationData.length > 0">
            <view class="li" v-for="(item, index) in stationData" :key="index">
                <view class="first">{{ index + 1 }}</view>
                <view class="second">{{ item.qxaa01A020 }}</view>
                <view class="third">{{ item.qxaa01A100 }}</view>
                <view class="fourth" @click="routerTo(item)">
                    <uv-image src="/static/rain/right.svg" width="50rpx" height="50rpx"></uv-image>
                </view>
            </view>
            <uv-gap height="120rpx"></uv-gap>
        </view>
        <uv-empty v-else marginTop="200rpx"></uv-empty>
    </view>
    <!-- 降雨时间类型 -->
    <uv-popup ref="popupRef" :zIndex="999" :round="10" :customStyle="{ margin: '0 60rpx', padding: '40rpx 20rpx' }">
        <view class="btns m20">
            <button :class="{ activeButton: timeTypeLive === 1 }" @click="changeTimeTypeLive(1)">
                1h
            </button>
            <button :class="{ activeButton: timeTypeLive === 3 }" @click="changeTimeTypeLive(3)">
                3h
            </button>
            <button :class="{ activeButton: timeTypeLive === 6 }" @click="changeTimeTypeLive(6)">
                6h
            </button>
            <button :class="{ activeButton: timeTypeLive === 12 }" @click="changeTimeTypeLive(12)">
                12h
            </button>
            <button :class="{ activeButton: timeTypeLive === 24 }" @click="changeTimeTypeLive(24)">
                24h
            </button>
            <button :class="{ activeButton: timeTypeLive === 48 }" @click="changeTimeTypeLive(48)">
                48h
            </button>
        </view>
    </uv-popup>
    <uv-datetime-picker ref="DatetimePicker" v-model="dataTime" mode="datetime" z-index="99999"
        @confirm="dataTimeConfirm"></uv-datetime-picker>
</template>

<script lang="ts" setup>
import rainMap from './components/rainMap.vue'
import {
    GetSelectByCityCountyAndTime_API,
    GetYLinfo_API,
} from '@/server/mapdzfz'
import { useUserStore } from '@/stores'
import dayjs from 'dayjs'
const store = useUserStore()
const { userInfo } = storeToRefs(store)

const dataTime = ref(dayjs().valueOf())
//用于展示页面
const startTimeCn = ref(
    dayjs().subtract(1, 'hour').format('YYYY年MM月DD日HH时'),
)
// 用于接口请求时间
let startTime = dayjs().subtract(1, 'hour').format('YYYY-MM-DD HH') //用于接口请求时间
// const tabCurrent = ref(1)
// const tabList = [
//     { name: '气象雨量站', id: 1 },
//     { name: '自建雨量站', id: 2 },
// ]
// const tabChange = (item) => {
//     tabCurrent.value = item.id
//     tabCurrent.value == 1 ? getList() : getList1()
// }
onLoad(() => {
    getList()
})
const DatetimePicker = ref()

/**
 * 打开日期选择器
 */
const openDate = () => {
    //转换时间戳
    dataTime.value = dayjs(startTime).valueOf()
    DatetimePicker.value.open()
}
const popupRef = ref()
const timePeriodQuery = () => {
    popupRef.value.open('center')
}

const timeTypeLive = ref(1)

const getNowTime = () => {
    // 自定义开始时间和结束时间
    if (timeTypeLive.value === 0) return
    startTimeCn.value = dayjs()
        .subtract(timeTypeLive.value, 'hour')
        .format('YYYY年MM月DD日HH时')
    startTime = dayjs()
        .subtract(timeTypeLive.value, 'hour')
        .format('YYYY-MM-DD HH')
}
const changeTimeTypeLive = (value) => {
    // 更换激活类型
    timeTypeLive.value = value
    popupRef.value.close()
    getNowTime()
    getList()
}
/**
 * 日期确定
 */
const dataTimeConfirm = (e) => {
    startTime = dayjs(e.value).format('YYYY-MM-DD HH')
    startTimeCn.value = dayjs(e.value).format('YYYY年MM月DD日HH时')
    timeTypeLive.value = 0
    getList()
}
const stationData = ref([])
const loading = ref(false)

const getList = async () => {
    try {
        uni.showLoading({ title: '加载中...' })
        objMax.value = {}
        stationData.value = []
        loading.value = true
        const data = {
            city: '',
            county: userInfo.value.AdminName,
            observationTime: dayjs(startTime).format('YYYY-MM-DD HH:00:00'),
        }
        const data1 = {
            current: '1',
            size: 100,
            areaCode: userInfo.value.AdminCode,
            beginMonitorTime: dayjs(startTime).format('YYYY-MM-DD HH:00:00'),
            endMonitorTime: dayjs().format('YYYY-MM-DD HH:00:00'),
        }
        const [res, res1] = await Promise.all([GetSelectByCityCountyAndTime_API(data), GetYLinfo_API(data1)])
        let List = []
        if (res.status) {
            List = res.data.map((el) => ({
                ...el,
                qxaa01A080: Number(el.qxaa01A080 / 10000),
                qxaa01A070: Number(el.qxaa01A070 / 10000),
                type: 1
            }))

        }
        if (res1.code === 0) {
            const ld = res1.data.records.filter(item => item.devName == '村镇雨量（气象标准）').map(item => {
                const l = {
                    qxaa01A010: item.ylData[item.ylData.length - 1]?.sensorCode || '',
                    qxaa01A050: item.ylData[item.ylData.length - 1]?.storageTime || '',
                    devName: item.devName,
                    qxaa01A080: item.lat,
                    qxaa01A070: item.lon,
                    qxaa01A020: extractTownOrTownship(item.devLocation) ? extractTownOrTownship(item.devLocation) : item.devLocation,
                    // qxaa01A020: this.extractTownOrTownship(item.ylData[item.ylData.length - 1]?.address),
                    qxaa01A100: item.ylData[item.ylData.length - 1]?.totalValue || '0.0',
                    type: 2
                }
                return l
            })
            stationData.value = [...List, ...ld]
        }
        if (stationData.value.length > 0) sortStationData('desc')
    } catch (error) {
        console.log('error:', error)
    } finally {
        loading.value = false
        uni.hideLoading()
    }
}
const getList1 = async () => {
    try {
        uni.showLoading({ title: '加载中...' })
        objMax.value = {}
        stationData.value = []
        loading.value = true
        const res = await GetYLinfo_API({
            current: '1',
            size: 100,
            areaCode: userInfo.value.AdminCode,
            beginMonitorTime: dayjs(startTime).format('YYYY-MM-DD HH:00:00'),
            endMonitorTime: dayjs().format('YYYY-MM-DD HH:00:00'),
        })
        if (res.code === 0) {
            const ld = res.data.records
                .filter((item) => item.devName == '村镇雨量（气象标准）')
                .map((item) => {
                    const l = {
                        devName: item.devName,
                        qxaa01A080: item.lat,
                        qxaa01A070: item.lon,
                        qxaa01A020: extractTownOrTownship(item.devLocation)
                            ? extractTownOrTownship(item.devLocation)
                            : item.devLocation,
                        // qxaa01A020: this.extractTownOrTownship(item.ylData[item.ylData.length - 1]?.address),
                        qxaa01A100:
                            item.ylData[item.ylData.length - 1]?.totalValue ||
                            '0.0',
                    }
                    return l
                })
            stationData.value = ld
            if (stationData.value.length > 0) sortStationData('desc')
        }
    } catch (error) {
        console.log('error:', error)
    } finally {
        loading.value = false
        uni.hideLoading()
    }
}
const objMax = ref({})
const sortStationData = (order = 'asc') => {
    stationData.value.sort((a, b) => {
        return order === 'asc'
            ? a.qxaa01A100 - b.qxaa01A100
            : b.qxaa01A100 - a.qxaa01A100
    })

    if (order == 'desc') {
        objMax.value = stationData.value[0]
    }
}
const extractTownOrTownship = (address) => {
    if (!address) return ''
    // 查找"镇"或"乡"或"街道"的位置
    const townIndex = address.indexOf('镇')
    const townshipIndex = address.indexOf('乡')
    const streetIndex = address.indexOf('道')

    // 确定哪个字出现得更早
    let targetChar, targetIndex
    if (townIndex !== -1 && townshipIndex !== -1 && streetIndex !== -1) {
        if (townIndex < townshipIndex) {
            targetChar = '镇'
            targetIndex = townIndex
        } else if (townshipIndex < streetIndex) {
            targetChar = '乡'
            targetIndex = townshipIndex
        } else {
            targetChar = '道'
            targetIndex = streetIndex
        }
    } else if (townIndex !== -1) {
        targetChar = '镇'
        targetIndex = townIndex
    } else if (townshipIndex !== -1) {
        targetChar = '乡'
        targetIndex = townshipIndex
    } else if (streetIndex !== -1) {
        targetChar = '道'
        targetIndex = streetIndex
    } else {
        // 如果都没有找到，返回空或根据需求处理
        return ''
    }
    // 从最近的"县"或开头开始截取到"镇"或"乡"
    let startIndex = address.lastIndexOf('县', targetIndex)
    startIndex = startIndex === -1 ? 0 : startIndex + 1

    // 截取包含"镇"或"乡"或"街道"的部分

    return address.substring(startIndex, targetIndex + 1)
}
// 给实况中站点数据颠倒
const reverseStationData = () => {
    stationData.value.reverse()
}

const routerTo = (item) => {
    uni.navigateTo({
        url: './stationEcharts/stationEcharts',
    })
}
</script>

<style lang="scss" scoped>
.time-container {
    padding: 10rpx 30rpx;

    .time {
        margin: 8rpx 0;
        width: 70%;
    }
}

.btns {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;

    button {
        color: inherit;
        font: inherit;
        width: 200rpx;
        height: 50rpx;
        line-height: 50rpx;
        background-color: transparent;
        border-radius: 12rpx;
    }

    .activeButton {
        background: #1989fa;
        border: none;
        // height: 50rpx;
        // line-height: 50rpx;
    }
}

.station-container {

    // margin-top: 20px;
    .m20 {
        margin: 0 20rpx;
    }

    .top {
        display: flex;
        width: 100%;
        // height: 60rpx;
        // line-height: 60rpx;
        text-align: center;
        background: #dce4f7;
        padding: 20rpx 0;
        // position: fixed;
        // top: 0;
    }

    .content {
        .li {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 6rpx 0;
            // height: 60rpx;
            text-align: center;

            &:nth-child(even) {
                background-color: #3ab8ef21;
            }
        }
    }

    .first {
        width: 15%;
    }

    .second {
        width: 55%;
    }

    .third {
        width: 15%;
    }

    .fourth {
        width: 15%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    img {
        width: 50rpx;
    }
}
</style>
